package org.example.projectdemo.advice;

import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import jakarta.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 * 统一处理控制器层的异常
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理表单验证异常（@Valid 触发的异常）
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ErrorResponse> handleValidationException(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();

        // 收集所有字段错误
        for (FieldError error : ex.getBindingResult().getFieldErrors()) {
            errors.put(error.getField(), error.getDefaultMessage());
        }

        // 构建统一错误响应
        ErrorResponse response = new ErrorResponse("VALIDATION_FAILED", "数据验证失败");
        response.setErrors(errors);

        return ResponseEntity.badRequest().body(response);
    }

    /**
     * 处理参数验证异常（@RequestParam @PathVariable 触发的异常）
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<ErrorResponse> handleConstraintViolationException(ConstraintViolationException ex) {
        ErrorResponse response = new ErrorResponse("PARAMETER_INVALID", "参数验证失败");
        Map<String, String> errors = new HashMap<>();
        errors.put("details", ex.getMessage());
        response.setErrors(errors);

        return ResponseEntity.badRequest().body(response);
    }

    /**
     * 处理业务逻辑异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ErrorResponse> handleIllegalArgumentException(IllegalArgumentException ex) {
        ErrorResponse response = new ErrorResponse("INVALID_ARGUMENT", ex.getMessage());
        return ResponseEntity.badRequest().body(response);
    }

    /**
     * 处理所有其他异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleGeneralException(Exception ex) {
        ErrorResponse response = new ErrorResponse("INTERNAL_ERROR", "系统内部错误，请稍后重试");
        
        // 在生产环境中应该记录日志，而不是返回详细错误信息
        ex.printStackTrace();

        return ResponseEntity.internalServerError().body(response);
    }
}